package com.cmy.common.config;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

/**
 * 缓存管理类
 * @Author:Cmy
 * @Date:2023-11-08 14:45
 */
@Slf4j
@EnableCaching//开启基于注解的缓存
@Configuration
public class CaffeineCacheConfig {

    /**
     * 如果一个项目中存在多种实现的CacheManager
     * 1.使用@Primary指定默认先加载哪个bean
     * 2.@Cacheable接口 指定具体的cacheManager
     * @return
     */
    @Bean("caffeineCacheManager")
    public CaffeineCacheManager CaffeineCacheManager(){
        CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager();
        //不缓存空值
        caffeineCacheManager.setAllowNullValues(false);
        //Caffeine配置 可以注入多个cacheName的cache
        Cache<Object, Object> commonCache = Caffeine.newBuilder()
                .expireAfterWrite(5, TimeUnit.HOURS)//写入后5hours过期
                .maximumSize(1000)//最大数量为100
                .build();
        caffeineCacheManager.registerCustomCache("common",commonCache);
        return caffeineCacheManager;
    }

}

    